#include <loglevel.hpp>
#include <timing/clock.hpp>
#include <usrtctx.hpp>

namespace usrtos {	

	LogLevel	SYSLOG;
	LogLevel	 DEBUG;
	LogLevel	  INFO;
	LogLevel	  WARN;
	LogLevel	 ERROR;
	LogLevel	 FATAL;

	namespace timing {
		CPU2SYS * CPUClock::c2s = nullptr;
		CPU2SYS * SYSClock::c2s = nullptr;
	};
};
extern "C" {
	void *context(const char* tmp) {
		auto r = new usrtos::CTX(tmp);
		printf("context @%s\n",tmp);
		return (void*)r;
	};
	int log_len(void *h,int l) {
		auto r = (usrtos::CTX*)h;
		return r->log_len(l);
	};
	void* getLog(void *h,int l) {
		auto r = (usrtos::CTX*)h;
		return (void *)r->getLog(l);
	};
	void uuid(void *h, const char*name, void*puuid) {
		auto r = (usrtos::CTX*)h;
		std::stringstream ln;
		ln << name;
		auto u = r->getMemKey(ln.str());
		memcpy(puuid,&u,sizeof(u));
	};
	bool Lp2Gp(void *h, void *gp, void *p, uint64_t size) {
		usrtos::CPBlock::GP& ngp = *((usrtos::CPBlock::GP*)(gp));
		auto r = (usrtos::CTX*)h;
		auto ret = r->L2G<char>(ngp,(char*)p);
		ngp.objsize = size;
		return ret;
	};
	bool UsrtAlloc(void *h, const char*name, void *gp, uint64_t size) {
		auto r = (usrtos::CTX*)h;
		std::stringstream ln;
		ln << name;
		auto mem = r->bindBlock<usrtos::Layout::UsrtMem>(ln.str());
		if(mem==nullptr) {
			return false;
		}
		usrtos::CPBlock::GP& ngp = *((usrtos::CPBlock::GP*)(gp));
		mem->newGP<char>(ngp,size,32);
		return true;
	};
	void* MemAlloc(void *m, void *gp, uint64_t size) {
		auto mem = (usrtos::Layout::UsrtMem*)m;
		usrtos::CPBlock::GP& ngp = *((usrtos::CPBlock::GP*)(gp));
		return (void*)mem->newGP<char>(ngp,size,32);
	};
	void* UrstBindMem(void *h, const char*name) {
		auto r = (usrtos::CTX*)h;
		std::stringstream ln;
		ln << name;
		auto mem = r->bindBlock<usrtos::Layout::RawMem>(ln.str());
		return (void*)mem;
	};
	void* UrstBindFifo(void *h, const char*name) {
		auto r = (usrtos::CTX*)h;
		std::stringstream ln;
		ln << name;
		auto mem = r->bindBlock<usrtos::Layout::UsrtFifo>(ln.str());
		return (void*)mem;
	};
	void *RawGetBuf(void* m,uint64_t from) {
		auto mem = (usrtos::Layout::RawMem*)m;
		return (void *)mem->getBuf(from);
	};
	void *RawGetAppdata(void* m) {
		auto mem = (usrtos::Layout::RawMem*)m;
		return mem->getAppdata();
	};
	size_t RawGetPos(void* m) {
		auto mem = (usrtos::Layout::RawMem*)m;
		return mem->getPos();
	};
	void RawSetPos(void* m, size_t pos) {
		auto mem = (usrtos::Layout::RawMem*)m;
		return mem->setPos(pos);
	};	
}; //extern "C"